import random
import string
from datetime import datetime

from flask import Flask, request, send_file

import Information
from blind_watermark import WaterMark

app = Flask(__name__)

OUTPUT_FOLD = "../examples/output/"


@app.after_request
def cors(environ):
    environ.headers['Access-Control-Allow-Origin'] = '*'
    environ.headers['Access-Control-Allow-Method'] = '*'
    environ.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type'
    return environ


# get请求
# 获得图片
@app.route('/getImage', methods=['get'])
def get_image():
    ip = str(request.remote_addr)
    user_agent = str(request.user_agent).replace(',', '_').replace('/', '_').replace('.', '_')
    user_name = "user01"
    date = str(datetime.now())

    print("ip: " + str(ip))
    print("user_agent: " + str(user_agent))
    print("user_name: " + user_name)
    print("date: " + str(date))

    # 生成嵌入水印后的图片
    Information.getPicture(ip, user_name, date)
    # 嵌入水印后的图片路径
    embed_img_path = OUTPUT_FOLD + 'embed_img_' + user_name + '.png'

    return send_file(embed_img_path, mimetype='image/png')


# post请求
# 上传图片
# 返回解水印后的二维码图片
@app.route('/getQrByImage', methods=['post'])
def get_qr_by_image():
    # 获取图片文件
    img = request.files.get('upload')

    # 获得水印尺寸
    wm_img_pix_map = (150, 150)

    # 重命名图片名称
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))
    img_name = ran_str + "_" + img.filename

    # 保存图片
    # 保存在example/output里
    img.save(OUTPUT_FOLD + img_name)

    # 解水印
    bwm1 = WaterMark(password_wm=1, password_img=1)
    wm_extracted_path = OUTPUT_FOLD + 'wm_extracted_' + img_name
    bwm1.extract(filename=OUTPUT_FOLD + img_name, wm_shape=wm_img_pix_map, out_wm_name=wm_extracted_path, )

    return send_file(wm_extracted_path, mimetype='image/png')

# post请求
# 上传图片和字符串
# 返回嵌入水印后的图片
@app.route('/getEmbeddedByImageAndStr', methods=['post'])
def get_embedded_by_image_and_str():
    # 获取图片文件
    img = request.files.get('upload')

    # 重命名图片名称
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))
    img_name = ran_str + "_" + img.filename

    # 保存图片
    # 保存在example/output里
    img.save(OUTPUT_FOLD + img_name)

    # 获得字符串
    str = request.form['str']

    # 根据字符串获得要嵌入的图片
    file_name = Information.embedded_by_image_and_str(img_name, str)

    return send_file(OUTPUT_FOLD + file_name, mimetype='image/png')

# post请求
# 解水印文本
@app.route('/getStrByImage', methods=['post'])
def get_str_by_image():
    # 获取图片文件
    img = request.files.get('upload')

    # 重命名图片名称
    ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))
    img_name = ran_str + "_" + img.filename

    # 保存图片
    # 保存在example/output里
    img.save(OUTPUT_FOLD + img_name)

    # 提取文本
    str = Information.getStrByImage(img_name)

    return str


app.run(host='0.0.0.0', port=8802, debug=True)
